﻿using System.Xml.Linq;
using iTransact.Requests;

namespace iTransact.Xml
{
	public static class AuthTransactionXml 
	{
		public static string Generate(Request request)
		{
			return GatewayXml.GenerateGatewayXml(request.iTransactUserName, request.iTransactGateway, request.iTransactApiKey, GenerateRequest(request));
		}

		static XElement GenerateRequest(Request request)
		{
			var authTransaction = new XElement("AuthTransaction");

			if (!string.IsNullOrEmpty(request.AuthCode))
				authTransaction.Add(new XElement("AuthCode", request.AuthCode));

			if (!string.IsNullOrEmpty(request.PreAuth))
				authTransaction.Add(new XElement("Preauth", request.PreAuth));

			// Add CustomerData
			authTransaction.Add(XmlSegments.CustomerData(request));

			// Order Items
			authTransaction.Add(XmlSegments.TotalsAndItems(request));

			// Accoung Information
			authTransaction.Add(XmlSegments.AccountInformation(request));

			// See if it's a reocurring request
			if (request.GetType() == typeof(ReocurringRequest))
				authTransaction.Add(XmlSegments.RecurringData((ReocurringRequest)request));

			// Add Transaction Control
			authTransaction.Add(XmlSegments.TransactionControl(true, true, request.TestMode, null));

			// Add Vendor Data
			if (request.MetaData != null && request.MetaData.Keys.Count > 0)
				authTransaction.Add(XmlSegments.VendorData(request));

			return authTransaction;
		}
	}
}
